package com.improve.frame.log.service.impl;

import com.improve.frame.log.domain.SysLog;
import com.improve.frame.log.properties.LogDbProperties;
import com.improve.frame.log.service.LogService;
import com.improve.frame.log.service.SysLogService;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;

import javax.sql.DataSource;

/**
 * @Description 日志实现类-数据库
 * @Author wzxing918
 * @Date 2021-03-31
 * @Version 1.0.0
 **/
@Slf4j
@ConditionalOnProperty(name = "improve.log.log-type", havingValue = "db")
@ConditionalOnClass(JdbcTemplate.class)
public class DbLogServiceImpl implements LogService {
    @Autowired
    private SysLogService sysLogService;

    private static final String INSERT_SQL = "INSERT INTO `sys_log` (`request_url`, `request_method`, `request_param`, `method_name`, `module_name`, `operator_code`, `operator_name`, `operation_ip`, `operation_client`, `operation_browser`, `browser_version`, `operation_type`, `operation_desc`,\n" +
            "`business_status`, `operation_result`, `response_result`, `operation_time`, `error_msg`)\n" +
            "VALUES\n" +
            "\t( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )";
    private final JdbcTemplate jdbcTemplate;

    public DbLogServiceImpl(@Autowired(required = false) LogDbProperties logDbProperties, DataSource dataSource) {
        //优先使用配置的日志数据源，否则使用默认的数据源
        if (logDbProperties != null && StringUtils.isNotEmpty(logDbProperties.getJdbcUrl())) {
            dataSource = new HikariDataSource(logDbProperties);
        }
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public void init() {
        String sql = "CREATE TABLE IF NOT EXISTS `sys_log`  (\n" +
                "  `id` bigint(20) NOT NULL AUTO_INCREMENT,\n" +
                "  `request_url` varchar(1024) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '请求路径',\n" +
                "  `request_method` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '请求方式',\n" +
                "  `request_param` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '请求参数',\n" +
                "  `method_name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '请求方法',\n" +
                "  `module_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '系统资源，指操作的模块，即资源管理里面的菜单',\n" +
                "  `operator_code` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '操作人ID',\n" +
                "  `operator_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '操作人姓名',\n" +
                "  `operation_ip` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '操作人IP',\n" +
                "  `operation_client` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '操作客户端',\n" +
                "  `operation_browser` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '操作浏览器',\n" +
                "  `browser_version` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '浏览器版本',\n" +
                "  `operation_type` tinyint(4) NULL DEFAULT NULL COMMENT '操作类型-参照枚举类型',\n" +
                "  `operation_desc` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '操作描述',\n" +
                "  `business_status` tinyint(4) NULL DEFAULT 0 COMMENT '业务状态',\n" +
                "  `operation_result` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '操作结果',\n" +
                "  `response_result` longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '响应结果',\n" +
                "  `operation_time` int(11) NULL DEFAULT NULL COMMENT '操作耗时',\n" +
                "  `error_msg` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '异常堆栈',\n" +
                "  `create_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\n" +
                "  PRIMARY KEY (`id`) USING BTREE,\n" +
                "  INDEX `create_time_index`(`create_time`) USING BTREE\n" +
                ") ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '操作日志表' ROW_FORMAT = Dynamic";
        this.jdbcTemplate.execute(sql);
    }

    @Async
    @Override
    public void save(SysLog sysLog) {
        boolean save = sysLogService.save(sysLog);
        if (!save) {
            log.error("保存系统日志失败");
        }
        /*this.jdbcTemplate.update(INSERT_SQL, sysLog.getRequestUrl(), sysLog.getRequestMethod(), sysLog.getRequestParam(), sysLog.getMethodName(),
                sysLog.getModuleName(), sysLog.getOperatorCode(), sysLog.getOperatorName(), sysLog.getOperationIp(), sysLog.getOperationClient(),
                sysLog.getOperationBrowser(), sysLog.getBrowserVersion(), sysLog.getOperationType(), sysLog.getOperationDesc(), sysLog.getBusinessStatus(),
                sysLog.getResponseResult(), sysLog.getResponseResult(), sysLog.getOperationTime(), sysLog.getErrorMsg());*/
    }
}
